package com.sinoglobal.dumping.net;

import android.content.Context;
import android.content.pm.PackageManager;

import com.sinoglobal.dumping.base.Dumpling_SinoConfig;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.base.Dumpling_SinoLogUtil;
import com.sinoglobal.dumping.exception.Dumpling_NoDataException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ty
 * @createdate 2012-9-19 上午10:40:06
 * @Description: Http请求
 */
public class LogIn_ConnectionUtil {

	public static final String URL = Dumpling_SinoConstans.LOGIN_USERCENTER_INTERFACE;

	private static final String ACCEPT = "Accept-Charset";
	private static final String UTF8 = "UTF-8";
	private static final String UTF8_ES = "UTF-8,*";
	private static final String REQUEST_URL = "请求：URL:-->:";
	private static final String RESPONSE_STATUS = "响应状态码：";
	private static final String RESPONSE_PARAMS = "---返回的参数为--->>：";

	/**
	 * 
	 * @author zrh
	 * @methods post 以键值对方式向服务器提交数据
	 * @description 以键值对方式向服务器提交数据
	 * @date 2014-11-18 上午9:51:48
	 * @param params
	 *            对应 NameValuePair的 key value
	 * @return 响应数据
	 * @throws Exception
	 *             各种异常交给业务处理
	 */
	public static String post(String index, Map<String, Object> params)
			throws Exception {
		String postUrl = URL + index;
		Dumpling_SinoLogUtil.d(REQUEST_URL + postUrl);
		HttpPost httpost = new HttpPost(postUrl);

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		StringBuffer sb =null;
		if (Dumpling_SinoConfig.sLogSwitch) {// 调试
			sb = new StringBuffer();
			sb.append(REQUEST_URL + postUrl + "?");
		}
		if (params != null) {
			for (String key : params.keySet()) {
				nvps.add(new BasicNameValuePair(key,
						params.get(key) == null ? "" : params.get(key)
								.toString()));
				Dumpling_SinoLogUtil.e("key:" + key + ", value:" + params.get(key));
				if (Dumpling_SinoConfig.sLogSwitch) {
					sb.append(key).append("=").append(params.get(key))
							.append("&");
				}
			}
			if (Dumpling_SinoConfig.sLogSwitch) {
				sb.deleteCharAt(sb.lastIndexOf("&"));
				Dumpling_SinoLogUtil.i("请求" + sb.toString());
			}
			params.clear();
		}
		httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
		return execute(httpost);
	}





	private static String execute(HttpUriRequest req) throws Exception {
		
		long startTime = System.currentTimeMillis();
		String result = null;
		HttpResponse response = executeLoad(req);
		if (response != null) {
			int statusCode = response.getStatusLine().getStatusCode();
			Dumpling_SinoLogUtil.d(RESPONSE_STATUS + statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity(), UTF8);
			} else if (statusCode == HttpStatus.SC_FORBIDDEN) { // 验证未通过

			} else if (statusCode == HttpStatus.SC_NOT_FOUND) { // 请求错误

			}
		}

		// 打包时应该注释
		long endTime = System.currentTimeMillis();
		String info = "请求：Time:" + (endTime - startTime) + "-->:"
				+ req.getURI();
		Dumpling_SinoLogUtil.d(info);
		if (result == null || "".equals(result.trim())) {
			throw new Dumpling_NoDataException("request not data :" + req.getURI());
		}
		Dumpling_SinoLogUtil.d(RESPONSE_PARAMS + result);
		return result;
	}

	/**
	 * @author ty
	 * @createdate 2012-11-3 下午9:46:54
	 * @Description: 加载数据
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse executeLoad(HttpUriRequest req) throws Exception {
		HttpClient httpclient = LogIn_CustomerHttpClient.getInstance();
		httpclient = LogIn_CustomerHttpClient.getInstance();
		req.addHeader(ACCEPT, UTF8_ES);
		HttpResponse response = httpclient.execute(req);
		return response;
	}

	/**
	 * 微信支付所需
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean checkApkExist(Context context, String packageName){
		if (packageName == null || "".equals(packageName)) {
			return false;
		}   try  {
			context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		}  catch (PackageManager.NameNotFoundException e)  {
			return false;  }
	}
}
